//登录与注册
import {reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLogout} from "@/api";
import {setToken,getToken,removeToken} from "@/utils/token";

const state={
  code:"",
  token:getToken(),
  userInfo:{
    userInfo:{
      email:"",
      gmtCreate:"",
      gmtModified:"",
      username:"",
      uid:"",
      phone:"",
      password:"",
      isDeleted:""
    }
  }
}
const mutations={
  GETCODE(state,code){
    state.code = code
  },
  USERLOGIN(state,token){
    state.token = token
  },
  GETUSERINFO(state,userInfo){
    state.userInfo = userInfo
  },
  //清除本地数据
  CLEAR(state){
    state.token='';
    state.userInfo={}
    //本地存储清空
    removeToken()
  }
}
const actions={
  //获取验证码
  async getCode({commit},phone){
    //获取验证码接口，后台把验证码发到用户手机上
    let result = await reqGetCode(phone)
    if (result.code===20000){
      commit("GETCODE",result.data)
      return  'ok'
    }else {
      return Promise.reject(new Error('false'))
    }
  },
  //用户注册
  async userRegister({commit},user){
    let result = await reqUserRegister(user);
    if (result.code===20000){
      return 'ok'
    }else {
      return Promise.reject(new Error('false'))
    }
  },
  //登录业务
  async userLogin({commit},data){
    let result = await reqUserLogin(data)
    //服务器下发token，将来经常通过token找服务器要用户信息进行展示
    if (result.code===20000){
      //用户已经登陆成功且获取到token
      commit("USERLOGIN",result.data.token)
      //持久化存储token
      setToken(result.data.token)
      return 'ok'
    }else {
      return Promise.reject(new Error("false"))
    }
  },
  //获取用户信息
  async getUserInfo({commit}){
    let result = await reqUserInfo();
    if (result.code===20000){
      //提交用户信息
      commit("GETUSERINFO",result.data)
      return 'ok'
    }else {
      return Promise.reject(new Error('false'))
    }
  },
  //退出登录
  async userLogout({commit}){
    //向服务器发起一次请求，通知服务器清除token
    // let result = await reqLogout();
    // if (result.code===20000){
    //   commit("CLEAR")
    //   return 'ok'
    commit("CLEAR")
    // }else {
    //   return Promise.reject(new Error('false'))
    // }
  }
}
const getters={}
export default {
  state,
  mutations,
  actions,
  getters
}